<div class="layui-fluid layui-layout-admin">
    <blockquote class="layui-elem-quote layui-quote-nm">设置权限</blockquote>
    <form class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">请选择</label>
            <div class="layui-input-block">
                <div id="LAY-auth-tree-index"></div>
            </div>
        </div>
        <div class="layui-form-item">
        	<div class="layui-input-block">
        		<div class="layui-footer">
					<input type="hidden" name="id" value="0">
					<button class="layui-btn" lay-submit lay-filter="LAY-send-submit">立即提交</button>
				</div>
			</div>
        </div>
    </form>
</div>

<script type="text/html" template lay-done="layui.data.sendParams(d.params)">
</script>

<script >
	layui.data.sendParams = function(params){
		layui.use(['form', 'authtree'], function () {
			let $ = layui.$
				, form = layui.form, authtree = layui.authtree;

			$(".layui-form").attr('action', layui.setter.API_HOST + 'admin/role/set_auth')
			let _role_id = params.id;
			$("input[name='id']").val(_role_id);
			
			let _index = layer.load();
			layui.admin.req({
				url: layui.setter.API_HOST + 'admin/role/get_tree',
				data: {
					id: _role_id
				},
				done: function(res) {
					console.log(res);
					layer.close(_index);
					if (res.code == 0) {
						// 渲染时传入渲染目标ID，树形结构数据（具体结构看样例，checked表示默认选中），以及input表单的名字
						authtree.render('#LAY-auth-tree-index', res.tree, {
							inputname: 'auth_ids[]',
							layfilter: 'lay-check-auth',
							openall: true,
							autowidth: true,
							nameKey: "title",
							valueKey: 'id',
							childKey: 'child'
						});
					} else {
						layer.msg('请求失败', {icon: 5})
					}
				}
			});

			form.on('checkbox(lay-check-auth)', function(data){
				// 注意这里：需要等待事件冒泡完成，不然获取叶子节点不准确。
				setTimeout(function(){
					// 获取选中的叶子节点
					let leaf = authtree.getLeaf('#LAY-auth-tree-index');
					console.log(leaf);
				}, 100);
			});

			/**
			 * 列表加载完成之后的回调函数
			 * @param d
			 */
			layui.data.done = function(d){
				console.log(d);
				layui.use(['form'], function(){
					form.render(null, 'component-form-group');
				});
			};
		});
	}
</script>